package com.thl.filechooser;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


public class FileAdapter extends CommonAdapter<FileInfo> {

    //    private int sign = -1;
    private int chooseCount = 1;
    private String chooseType;
    private FileChooserActivity.SelectAllListener selectAllListener;
    //List<FileInfo> selectList = new ArrayList<>();
    //选中的都放在这里
    LinkedHashMap<String, FileInfo> selectMap = new LinkedHashMap<>();
    /**
     * 是否所有文件可以选择，就显示所有的checkbox，为true，就忽略 issShowOtherNoSelectFile
     */
    private boolean isAllFileAllowSelect = false;

    public FileAdapter(Context context, ArrayList<FileInfo> dataList, int resId, String chooseType, int chooseCount, FileChooserActivity.SelectAllListener selectAllListener) {
        super(context, dataList, resId);
        this.chooseType = chooseType;
        this.chooseCount = chooseCount;
        this.selectAllListener = selectAllListener;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void bindView(RecyclerView.ViewHolder holder, final FileInfo data, final int position) {
        TextView textView = (TextView) holder.itemView.findViewById(R.id.fileName);
        TextView textTime = (TextView) holder.itemView.findViewById(R.id.fileTime);
        TextView fileSize = (TextView) holder.itemView.findViewById(R.id.fileSize);
        textView.setText(data.getFileName());
        textTime.setText(data.getCreateTime());
        if (data.isFolder()) {
            String newPath = data.getFilePath();
            if (FileTourController.isReadAbsoluteData){
                String path = data.getFilePath();
                newPath = path.replace(FileTourController.dataPath,FileTourController.dataPathNoPremission);
            }
            File[] files = new File(newPath).listFiles();
            fileSize.setText("0项");
            if (null != files) {
                fileSize.setText(files.length + "项");
            }

        } else {
            fileSize.setText(getFileSize(data.getFilePath()));
        }

        ImageView imageView = (ImageView) holder.itemView.findViewById(R.id.fileIcon);
        ImageView fileTypeIcon = (ImageView) holder.itemView.findViewById(R.id.fileTypeIcon);

        imageView.setOnClickListener(v -> {
            if (FileInfo.FILE_TYPE_VIDEO.equals(data.getFileType())) {
                launcherActivity(imageView.getContext(), "com.mycp.videocompress.ui.player.VideoPlayerActivity", data.getFilePath());
            } else if (FileInfo.FILE_TYPE_AUDIO.equals(data.getFileType())) {
                openMusic(imageView.getContext(), data.getFilePath());
            } else if (FileInfo.FILE_TYPE_APK.equals(data.getFileType())) {
                openFile(v.getContext(), data.getFilePath());
            } else if (FileInfo.FILE_TYPE_ZIP.equals(data.getFileType()) || FileInfo.FILE_TYPE_RAR.equals(data.getFileType())) {
                openFile(v.getContext(), data.getFilePath());
            } else if (FileInfo.FILE_TYPE_JPEG.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_JPG.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_WEBP.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_GIF.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_PNG.equals(data.getFileType())) {
                launcherActivity(imageView.getContext(), "com.mycp.videocompress.ui.player.ImagePreviewActivity", data.getFilePath());
            } else if (FileInfo.FILE_TYPE_FOLDER.equals(data.getFileType())) {
                imageView.setImageResource(R.drawable.format_folder);
            } else {
                openFile(v.getContext(), data.getFilePath());
            }

        });
        fileTypeIcon.setVisibility(View.GONE);
        if (FileInfo.FILE_TYPE_VIDEO.equals(data.getFileType())) {
            FileChooserGlide.displayVideo(imageView.getContext(), imageView, data.getFilePath());
            fileTypeIcon.setVisibility(View.VISIBLE);
        } else if (FileInfo.FILE_TYPE_AUDIO.equals(data.getFileType())) {
            imageView.setImageResource(R.drawable.format_music);
        } else if (FileInfo.FILE_TYPE_APK.equals(data.getFileType())) {
            imageView.setImageResource(R.drawable.format_app);
        } else if (FileInfo.FILE_TYPE_ZIP.equals(data.getFileType()) || FileInfo.FILE_TYPE_RAR.equals(data.getFileType())) {
            imageView.setImageResource(R.drawable.format_compress);
        } else if (FileInfo.FILE_TYPE_JPEG.equals(data.getFileType())
                || FileInfo.FILE_TYPE_JPG.equals(data.getFileType())
                || FileInfo.FILE_TYPE_WEBP.equals(data.getFileType())
                || FileInfo.FILE_TYPE_GIF.equals(data.getFileType())
                || FileInfo.FILE_TYPE_PNG.equals(data.getFileType())) {
            FileChooserGlide.display(imageView, data.getFilePath());
        } else if (FileInfo.FILE_TYPE_FOLDER.equals(data.getFileType())) {
            imageView.setImageResource(R.drawable.format_folder);
        } else {
            imageView.setImageResource(R.drawable.format_other);
        }

        ImageView fileChoose = (ImageView) holder.itemView.findViewById(R.id.fileChoose);
        if (data.isCheck()) {
            fileChoose.setImageResource(R.drawable.log_choose_checkbox_on);
        } else {
            fileChoose.setImageResource(R.drawable.log_choose_checkbox_off);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mItemClickListener != null) {
                    mItemClickListener.onItemClick(v, position, data);
                }
            }
        });
        if (isAllFileAllowSelect || chooseType.equals(FileInfo.FILE_TYPE_ALL)) {
            //所有文件可选，把所有文件加入进去
            fileChoose.setVisibility(View.VISIBLE);
            fileChoose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    notifyData(position);
                }
            });
        } else {
            if (chooseType.equals(FileInfo.FILE_TYPE_FILE)){
                if (data.isFolder()){
                    fileChoose.setVisibility(View.GONE);
                }else {
                    fileChoose.setVisibility(View.VISIBLE);
                }
            } else if (chooseType.equals(data.getFileType())) {
                fileChoose.setVisibility(View.VISIBLE);
                fileChoose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        notifyData(position);
                    }
                });
            } else if (chooseType.equals(FileInfo.FILE_TYPE_IMAGE)) {

                if (FileInfo.FILE_TYPE_JPEG.equals(data.getFileType())
                        || FileInfo.FILE_TYPE_JPG.equals(data.getFileType())
                        || FileInfo.FILE_TYPE_WEBP.equals(data.getFileType())
                        || FileInfo.FILE_TYPE_GIF.equals(data.getFileType())
                        || FileInfo.FILE_TYPE_PNG.equals(data.getFileType())) {

                    fileChoose.setVisibility(View.VISIBLE);
                    fileChoose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            notifyData(position);
                        }
                    });
                }else {
                    fileChoose.setVisibility(View.GONE);
                }

            } else if (chooseType.equals(FileInfo.FILE_TYPE_PACKAGE)) {
                if (FileInfo.FILE_TYPE_ZIP.equals(data.getFileType()) || FileInfo.FILE_TYPE_RAR.equals(data.getFileType())) {
                    fileChoose.setVisibility(View.VISIBLE);
                    fileChoose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            notifyData(position);
                        }
                    });
                }else {
                    fileChoose.setVisibility(View.GONE);
                }
            } else {
                fileChoose.setVisibility(View.GONE);
            }


//            if (chooseType.equals(FileInfo.FILE_TYPE_FOLDER)) {
//                boolean folder = data.isFolder();
//                if (folder) {
//                    fileChoose.setVisibility(View.VISIBLE);
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            notifyData(position);
//                        }
//                    });
//                } else {
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                        }
//                    });
//                    fileChoose.setVisibility(View.GONE);
//                }
//            } else if (chooseType.equals(FileInfo.FILE_TYPE_FILE)) {
//                boolean folder = data.isFolder();
//                if (!folder) {
//                    fileChoose.setVisibility(View.VISIBLE);
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            notifyData(position);
//                        }
//                    });
//                } else {
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                        }
//                    });
//                    fileChoose.setVisibility(View.GONE);
//                }
//            } else if (chooseType.equals(FileInfo.FILE_TYPE_IMAGE)) {
//
//                if (FileInfo.FILE_TYPE_JPEG.equals(data.getFileType())
//                        || FileInfo.FILE_TYPE_JPG.equals(data.getFileType())
//                        || FileInfo.FILE_TYPE_WEBP.equals(data.getFileType())
//                        || FileInfo.FILE_TYPE_GIF.equals(data.getFileType())
//                        || FileInfo.FILE_TYPE_PNG.equals(data.getFileType())) {
//
//                    fileChoose.setVisibility(View.VISIBLE);
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            notifyData(position);
//                        }
//                    });
//                } else {
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                        }
//                    });
//                    fileChoose.setVisibility(View.GONE);
//                }
//
//            } else if (chooseType.equals(FileInfo.FILE_TYPE_PACKAGE)) {
//                if (FileInfo.FILE_TYPE_ZIP.equals(data.getFileType()) || FileInfo.FILE_TYPE_RAR.equals(data.getFileType())) {
//                    fileChoose.setVisibility(View.VISIBLE);
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            notifyData(position);
//                        }
//                    });
//                } else {
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                        }
//                    });
//                    fileChoose.setVisibility(View.GONE);
//                }
//            } else {
//                if (chooseType.equals(data.getFileType())) {
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            notifyData(position);
//                        }
//                    });
//                    fileChoose.setVisibility(View.VISIBLE);
//                } else {
//                    fileChoose.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                        }
//                    });
//                    fileChoose.setVisibility(View.GONE);
//                }
//            }
        }
    }

    private ItemClickListener mItemClickListener;

    public void setItemClickListener(ItemClickListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }

    public interface ItemClickListener {
        void onItemClick(View view, int position, FileInfo data);
    }

    public void notifyClick(FileInfo data, int position) {
        if (chooseType.equals(FileInfo.FILE_TYPE_ALL)) {
            notifyData(position);
        } else if (chooseType.equals(FileInfo.FILE_TYPE_FOLDER)) {
            boolean folder = data.isFolder();
            if (folder) {
                notifyData(position);
            }
        } else if (chooseType.equals(FileInfo.FILE_TYPE_FILE)) {
            boolean folder = data.isFolder();
            if (!folder) {
                notifyData(position);
            }
        } else if (chooseType.equals(FileInfo.FILE_TYPE_IMAGE)) {
            if (FileInfo.FILE_TYPE_JPEG.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_JPG.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_WEBP.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_GIF.equals(data.getFileType())
                    || FileInfo.FILE_TYPE_PNG.equals(data.getFileType())) {
                notifyData(position);
            }
        } else if (chooseType.equals(FileInfo.FILE_TYPE_PACKAGE)) {
            if (FileInfo.FILE_TYPE_ZIP.equals(data.getFileType()) || FileInfo.FILE_TYPE_RAR.equals(data.getFileType())) {
                notifyData(position);
            }
        } else if (chooseType.equals(data.getFileType())) {
            notifyData(position);
        }
    }

    public int getSize() {
        return selectMap.size();
    }

    public List<FileInfo> getChooseFilePath() {
        return new ArrayList<>(selectMap.values());
    }

    public void notifyData() {
        notifyDataSetChanged();
    }

    public void notifyData(int position) {
        if (dataList.get(position).isCheck()) {
            dataList.get(position).setCheck(false);
            selectMap.remove(dataList.get(position).getFilePath());
        } else {
            if (selectMap.size() >= chooseCount) {
                Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                return;
            }
            dataList.get(position).setCheck(true);
            selectMap.put(dataList.get(position).getFilePath(), dataList.get(position));
        }
        //取消添加一个就要重新判断是不是全选
        selectAllListener.onSelectAll();
        notifyDataSetChanged();
    }

    // 全选时调用
    public void selectAllNotifyAllData(boolean isSelectAll) {
        int size = dataList.size();
        if (!isSelectAll) {
            selectMap.clear();
        }
        for (int i = 0; i < size; i++) {
            if (isAllFileAllowSelect){
                //所有文件可全选
                if (isSelectAll) {
                    if (selectMap.size() >= chooseCount) {
                        Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                        break;
                    }
                    dataList.get(i).setCheck(true);
                    selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                } else {
                    dataList.get(i).setCheck(false);
                }
            } else if (chooseType.equals(FileInfo.FILE_TYPE_FILE)) {
                //选择文件，不选文件夹
                if (!dataList.get(i).isFolder()) {
                    //如果是文件
                    if (isSelectAll) {
                        if (selectMap.size() >= chooseCount) {
                            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                            break;
                        }
                        dataList.get(i).setCheck(true);
                        selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                    } else {
                        dataList.get(i).setCheck(false);
                    }
                }
            } else if (chooseType.equals(FileInfo.FILE_TYPE_VIDEO)) {
                //全选视频
                if (FileInfo.FILE_TYPE_VIDEO.equals(dataList.get(i).getFileType())) {
                    //如果是视频
                    if (isSelectAll) {
                        if (selectMap.size() >= chooseCount) {
                            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                            break;
                        }
                        dataList.get(i).setCheck(true);
                        selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                    } else {
                        dataList.get(i).setCheck(false);
                    }
                }
            } else if (chooseType.equals(FileInfo.FILE_TYPE_IMAGE)) {
                //全选图片
                if (FileInfo.FILE_TYPE_JPEG.equals(dataList.get(i).getFileType())
                        || FileInfo.FILE_TYPE_JPG.equals(dataList.get(i).getFileType())
                        || FileInfo.FILE_TYPE_WEBP.equals(dataList.get(i).getFileType())
                        || FileInfo.FILE_TYPE_PNG.equals(dataList.get(i).getFileType())) {
                    //如果是图片
                    if (isSelectAll) {
                        if (selectMap.size() >= chooseCount) {
                            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                            break;
                        }
                        dataList.get(i).setCheck(true);
                        selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                    } else {
                        dataList.get(i).setCheck(false);
                    }
                }
            } else if (chooseType.equals(FileInfo.FILE_TYPE_GIF)) {
                //全选gif
                if (FileInfo.FILE_TYPE_GIF.equals(dataList.get(i).getFileType())) {
                    //如果是gif
                    if (isSelectAll) {
                        if (selectMap.size() >= chooseCount) {
                            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                            break;
                        }
                        dataList.get(i).setCheck(true);
                        selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                    } else {
                        dataList.get(i).setCheck(false);
                    }
                }
            } else if (chooseType.equals(FileInfo.FILE_TYPE_AUDIO)) {
                //全选音频
                if (FileInfo.FILE_TYPE_AUDIO.equals(dataList.get(i).getFileType())) {
                    if (isSelectAll) {
                        if (selectMap.size() >= chooseCount) {
                            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                            break;
                        }
                        dataList.get(i).setCheck(true);
                        selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                    } else {
                        dataList.get(i).setCheck(false);
                    }
                }
            } else if (chooseType.equals(FileInfo.FILE_TYPE_FOLDER)) {
                //选择文件夹，不选文件
                if (dataList.get(i).isFolder()) {
                    //如果是文件夹
                    if (isSelectAll) {
                        if (selectMap.size() >= chooseCount) {
                            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                            break;
                        }
                        dataList.get(i).setCheck(true);
                        selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                    } else {
                        dataList.get(i).setCheck(false);
                    }
                }
            } else {
                //不区分文件和文件夹，全部选中
                if (isSelectAll) {
                    if (selectMap.size() >= chooseCount) {
                        Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
                        break;
                    }
                    dataList.get(i).setCheck(true);
                    selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
                } else {
                    dataList.get(i).setCheck(false);
                }
            }
        }
        notifyDataSetChanged();
    }

    /**
     * 区间选择
     */
    @SuppressLint("NotifyDataSetChanged")
    public void intervalSelectAll() {
        int size = dataList.size();
        if (selectMap.size() < 2) {
            Toast.makeText(context, "区间选择必须选中两个以上", Toast.LENGTH_LONG).show();
            return;
        }
        if (selectMap.size() >= chooseCount) {
            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
            return;
        }
        List<Integer> indexList = new ArrayList<>();
        for (String s : selectMap.keySet()) {
            for (int i = 0; i < size; i++) {
                if (s.equals(dataList.get(i).getFilePath())) {
                    indexList.add(i);
                }
            }
        }
        int first = FileChooserListUtils.INSTANCE.getMinByList(indexList);
        int last = FileChooserListUtils.INSTANCE.getMaxByList(indexList);
        if (last - first >= chooseCount) {
            Toast.makeText(context, "最多选择" + chooseCount + "个", Toast.LENGTH_LONG).show();
            return;
        }
        for (int i = 0; i < size; i++) {
            if (i >= first && i <= last) {
                dataList.get(i).setCheck(true);
                selectMap.put(dataList.get(i).getFilePath(), dataList.get(i));
            }
        }
        notifyDataSetChanged();
    }


    @Override
    public void setData(List<FileInfo> infoList) {
        int size = infoList.size();
        for (int i = 0; i < size; i++) {
            if (selectMap.containsKey(infoList.get(i).getFilePath())) {
                //相同的路径,说明已经被选中了
                infoList.get(i).setCheck(true);
            }
        }
        super.setData(infoList);
    }

    public boolean isAllFileAllowSelect() {
        return isAllFileAllowSelect;
    }

    public void setAllFileAllowSelect(boolean allFileAllowSelect) {
        isAllFileAllowSelect = allFileAllowSelect;
    }

    public static String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            DecimalFormat df = new DecimalFormat("#0.00");
            long size = f.length();
            float s = (size / 1024f) / 1024f;
            return df.format(s) + "MB";
        }
    }

    public static void launcherActivity(Context context, String className, String path) {
        try {
            Class<?> targetClass = Class.forName(className);
            Intent intent = new Intent(context, targetClass);
            intent.putExtra("path", path);
            context.startActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void openMusic(Context context, String path) {
        try {
            Class<?> targetClass = Class.forName("com.mycp.videocompress.util.FileUtil");
            // 获取参数类型数组
            Class<?>[] parameterTypes = {Context.class, String.class};
            Method method = targetClass.getMethod("openMp3ByDialog", parameterTypes);
            // 创建参数对象数组
            Object[] arguments = {context, path};
            // 调用静态方法
            method.invoke(null, arguments);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void openFile(Context context, String path) {
        try {
            Class<?> targetClass = Class.forName("com.mycp.videocompress.util.FileUtil");
            // 获取参数类型数组
            Class<?>[] parameterTypes = {Context.class, String.class};
            Method method = targetClass.getMethod("openFile", parameterTypes);
            // 创建参数对象数组
            Object[] arguments = {context, path};
            // 调用静态方法
            method.invoke(null, arguments);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
